import { getShopCartList, removeCartList, chengeCheck } from "@/api";

const state = {
  // 购物车数据
  CartList: [],
};

const mutations = {
  //设置购物车数据
  setCartList(state, data) {
    state.CartList = data;
  },
};
const actions = {
  //获取商品购物车列表
  async getCartList({ commit }) {
    const res = await getShopCartList();
    if (res.code == 200) {
      commit("setCartList", res.data);
    }
  },
  //删除购物车产品
  async removeCartList({ commit }, skuId) {
    const res = await removeCartList(skuId);
    if (res.code == 200) return "ok";
    return Promise.reject(new Error("失败！"));
  },
  //修改购物车选择的状态
  async chengeCheck({ commit }, { skuId, isChecked }) {
    const res = await chengeCheck(skuId, isChecked);
    if (res.code == 200) return "ok";
    return Promise.reject(new Error("失败！"));
  },
  //删除所有商品
  deleteAllGoods({ dispatch, getters }) {
    // context相当于仓库
    let PromiseAll = [];
    getters.CartList.cartInfoList.forEach((item) => {
      //如果勾选了，就执行删除，否则不执行
      let promise =
        item.isChecked == 1 ? dispatch("removeCartList", item.skuId) : "";
      //每一次返回的添加到数组
      PromiseAll.push(promise);
    });
    //都成功才返回成功，如果有一个失败，返回的就是失败
    return Promise.all(PromiseAll);
  },
  //修改全选的状态
  chanegAllChecked({ dispatch, state }, isChecked) {
    let PromiseAll = [];
    state.CartList[0].cartInfoList.forEach((item) => {
      let promise = dispatch("chengeCheck", {
        skuId: item.skuId,
        isChecked: isChecked,
      });
      PromiseAll.push(promise);
    });
    return Promise.all(PromiseAll);
  },
};
const getters = {
  CartList(state) {
    return state.CartList[0] || {};
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
